package com.oracle.dao;

import com.oracle.entity.Book;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BookDao {
    private List<Book> list = new ArrayList<Book>();
    public List<Book> selBookAll(){
        Connection connection=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/20230720?useSSL=FALSE&serverTimezone=UTC";
            String username="root";
            String password="123456";
            connection = DriverManager.getConnection(url, username, password);
            String sql="select * from book";
            ps = connection.prepareStatement(sql);
            rs=ps.executeQuery();
            while (rs.next()){
                Book book = new Book();
                book.setNum(rs.getInt("num"));
                book.setBookname(rs.getString("bookname"));
                book.setAuthor(rs.getString("author"));
                book.setCategory(rs.getString("category"));
                book.setPress(rs.getString("press"));
                book.setPrice(rs.getDouble("price"));
                book.setSell(rs.getDouble("sell"));
                book.setCount(rs.getInt("count"));
                list.add(book);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

        }
        return list;

    }
}
